<template>
  <el-dialog append-to-body
             :title="title"
             :visible.sync="dialogVisible"
             width="600px"
             @close="handleClose">

    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="选择数据源" prop="type">
        <el-select v-model="form.name" clearable>
          <el-option v-for="item in dataSourceList" :key="item.name"
                     :value="item.name"
                     :label="item.title"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <!--组件样式-->
    <component ref="dataSource" v-if="form.name" :is="form.name" :data-source="form"
               :dataType="activeElement.dataType"/>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
  import dataSources from "./index.js";
  import Device from './device/index';
  import vpd from '../designer/mixins/vpd';

  export default {
    mixins: [vpd],
    components: {
      Device
    },
    props: {
      ds: {
        type: Object
      }
    },
    data() {
      return {
        dialogVisible: true,
        form: {
          name: '',
        },
        dataSourceList: [],
        dataSourceComponent: ''
      }
    },
    computed: {
      title() {
        return '配置数据源';
      },
      activeElement() {
        return this.$vpd.state.activeElement;
      },
    },
    created() {
      if (this.activeElement.page) { // 全局数据源
        this.form = Object.assign(this.form, this.ds);
      } else {
        this.form = Object.assign(this.form, this.activeElement.dataSource);
      }

      this.dataSourceList = dataSources.list;
    },
    methods: {
      handleClose() {
        this.$emit('close');
      },
      handleSubmit() {
        //submit
        const data = this.$refs.dataSource.getForm();
        Object.assign(this.form, data);

        if (this.activeElement.page) { //全局的数据源
          this.$emit('success', this.form);

        } else { //组件的数据源
          this.$vpd.commit('dataSource', {
            uuid: this.activeElement.uuid,
            dataSource: this.form
          });

          this.$emit('close');
        }

      }
    }
  }
</script>
